package org.pwwong.fxscalautils.components.containers

import java.awt.{Dimension,Insets,Rectangle,Point}

import org.pwwong.fxscalautils.Predef._
import org.pwwong.fxscalautils.components.layouthints._
import org.pwwong.scalautils.property._

object Canvas {
  def apply() = new Canvas with AccessibleChildren
}

class Canvas extends Container {
    
  protected val _preferredWidth = Prop[Double]( 0.0 )  
  protected val _preferredHeight = Prop[Double]( 0.0 )  
  override lazy val preferredWidth = _preferredWidth  
  override lazy val preferredHeight = _preferredHeight
  
  override protected def layout {
    for( child <- children ){ 
      // Size child
      setWidth(child){
        child.w() match {
          case Preferred() => child.preferredWidth() 
          case PX(pxv) => pxv.toDouble
          case PCT(pctv) => (curWidth()*(pctv.toDouble/100.0))
          case Fill() => curWidth()
        }
      }
      setHeight(child){
        child.h() match {
          case Preferred() => child.preferredHeight()
          case PX(pxv) => pxv.toDouble
          case PCT(pctv) => (curHeight()*(pctv.toDouble/100.0))
          case Fill() => curHeight()
        }
      }
      
      // Layout Children on x-axis
      setX(child)(
        (child.x().origin match {
          case LeftOrigin => 0.0
          case CenterOrigin => curWidth()/2.0
          case RightOrigin => curWidth()
        }) +
          (child.x().offset match {
            case PX(pxv) => pxv.toDouble
            case PCT(pctv) => (curWidth()*(pctv/100.0))
          })
      )
      // Layout Children on y-axis
      setY(child)(
        (child.y().origin match {
          case TopOrigin => 0.0
          case MiddleOrigin => curHeight()/2.0
          case BottomOrigin => curHeight()
        }) +
          (child.y().offset match {
            case PX(pxv) => pxv.toDouble
            case PCT(pctv) => (curHeight()*(pctv/100.0))
          })
      )
    }
    
    // TODO
    /*def minMaxDim(curMinOrMax:Dimension, contenderX:Component=>Double, contenderY:Component=>Double, compare:(Int,Double)=>Boolean)(contender:Component):Dimension = {
      if( compare( curMinOrMax.width, contenderX(contender) ) ) curMinOrMax.width = contenderX(contender).toInt
      if( compare( curMinOrMax.height, contenderY(contender) ) ) curMinOrMax.height = contenderY(contender).toInt
      curMinOrMax
    }
    val min:Dimension = children().foldLeft[Dimension](new Dimension(0,0)){
      minMaxDim(_,_.x(),_.y(),_>_)(_)
    }
    val max:Dimension = children().foldLeft[Dimension](new Dimension(0,0)){
      minMaxDim(_,{c=>c.x()+c.curWidth()},{c=>c.y()+c.curHeight()},_<_)(_)
    }
    max.width -= min.width
    max.height -= min.height
    
    _minimumSize <= max
    _maximumSize <= max
    
    println("canvas layout: ("+maximumSize().width+","+maximumSize().height+")")*/
  }
}

